from zope.interface import implements
from zope.component import adapts, getMultiAdapter, queryUtility
from plone.app.portlets.portlets import base
from plone.memoize.instance import memoize
from plone.portlets.interfaces import IPortletDataProvider
from plone.app.layout.navigation.navtree import buildFolderTree
from Products.CMFPlone.utils import getToolByName

from plonetheme.apkntheme import APKNThemeMessageFactory as _, logger
from plonetheme.apkntheme.settings import COUNTRY_FOLDER_META
from plonetheme.apkntheme.browser.interfaces import IFolderContainerDashboard,\
                                                    IFolderCountryDashboard

from Acquisition import aq_inner, aq_parent
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile

COUNTRY_FOLDER_ROOT = '/Plone/apex/country-folders'

class ICountryNavigatorPortlet(IPortletDataProvider):
    """
    """
    
class Assignment(base.Assignment):
    implements(ICountryNavigatorPortlet)
    
    @property
    def title(self):
        return _('Country Content')
        
class Renderer(base.Renderer):
    def __init__(self, context, request, view, manager, data):
        base.Renderer.__init__(self, context, request, view, manager, 
        data)
    
    @property
    def portal_catalog(self):
        return getToolByName(self.context, 'portal_catalog', None)
    
    @property
    def is_anonymous(self):
        mtool = getToolByName(self.context, 'portal_membership', None)
        if mtool:
            return bool(mtool.isAnonymousUser())
        return True

    @property
    def available(self):
        return True

    @property
    def portal_url(self):
        return getToolByName(self.context, 'portal_url', None)

    @property
    def country_code(self):
        code = ''
        portal = self.portal_url.getPortalObject()
        base_object = portal.restrictedTraverse(self.base_url)
        if hasattr(base_object, COUNTRY_FOLDER_META):
            return getattr(base_object, COUNTRY_FOLDER_META)
        return code

    @property
    def base_url(self):
        current_path = '/'.join(self.context.getPhysicalPath())
        if not (current_path == COUNTRY_FOLDER_ROOT):
            current_object = aq_inner(self.context)
            if (IFolderContainerDashboard.providedBy(current_object) or
                IFolderCountryDashboard.providedBy(current_object)):
                return '/'.join(current_object.getPhysicalPath())
            else:
                not_found_root = True
                current_parent = self.context
                while not_found_root:
                    parent_object = aq_parent(current_parent)
                    if (IFolderContainerDashboard.providedBy(parent_object) or
                        IFolderCountryDashboard.providedBy(parent_object)):
                        not_found_root = False
                    elif (parent_object == self.portal_url.getPortalObject()):
                        return COUNTRY_FOLDER_ROOT
                    current_parent = parent_object
                return '/'.join(current_parent.getPhysicalPath())
        return COUNTRY_FOLDER_ROOT

    def nav_portlet_title(self):
        portal = self.portal_url.getPortalObject()
        folder = portal.restrictedTraverse(self.base_url)
        return folder.Title()

    def display_portlet(self):
	"""Display the portlet as long as it is not 'Country Folders'
	"""
	display_portlet = True
        portal_title = self.nav_portlet_title()
	logger.info("CURRENT TITLE IS : '%s'", portal_title)
	if str(portal_title).strip().lower() == str("Country Folders").lower():
	    display_portlet = False
        return display_portlet

    def country_content_tree(self):
        #if self.portal_url is not None:
        #    base_url = self.portal_url.getPortalPath()
        base_url = '/'.join(self.context.getPhysicalPath())
        #else:
        #    base_url = '/'
        query = dict(
                path = {'query':self.base_url,
                        'depth': 1},
                sort_on = "id",
            )
        #if self.is_anonymous:
        #    base_tree = {'children':[]}
        #else:
        base_tree = buildFolderTree(self.context, None, query)
            #if base_tree:
            #   if len(base_tree['children']):
            #        return base_tree['children'][0]
        return base_tree

    render = ViewPageTemplateFile("countrynavigator.pt")

class AddForm(base.AddForm):
    label = _("Add country navigator portlet")
    description = _("This portlet renders custom navigation for\
     country")
    
    def create(self, data):
        return Assignment()

class EditForm(base.EditForm):
    label = _("Edit country navigator portlet")
    description = _("This portlet renders custom navigation for \
    workspaces")
